package com.travelbug.io;

import org.junit.Test;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * IO流
 * 操作数据的单位                  字节点（byte）  字符流（char）
 * 数据的流向（针对内存、程序）       输入流         输出流
 * 流的功能角色                    节点流         处理流
 */
public class ReaderAndWriterTest2 {

    /**
     * 写法不规范
     *
     * @throws IOException
     */
    //字符输入流
    @Test
    public void testFileReader() throws IOException {

        File file = new File("hi.txt");

        FileReader fr = new FileReader(file);

        int read = fr.read();
        while (read != -1) {
            System.out.print((char) read);
            read = fr.read();
        }

        fr.close();
    }

    @Test
    public void testFileReader2() {
        FileReader fr = null;
        try {
            //确定流的端点
            File file = new File("hi.txt");
            //创建流
            fr = new FileReader(file);
            int read;
            while ((read = fr.read()) != -1) {
                System.out.print((char) read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @Test
    public void testFileReader3() {
        FileReader fr = null;
        try {
            //确定流的端点
            File file = new File("hi.txt");//不会抛出异常
            //创建流
            fr = new FileReader(file);//如果file在磁盘中不存在，会抛出FileNotFoundException
            int len;
            char buffer[] = new char[5];
//            while ((len = fr.read(buffer)) != -1) {
//                for (int i = 0; i < len; i++) {
//                    System.out.print(buffer[i]);
//                }
//            }
            while ((len = fr.read(buffer)) != -1) {//如果文件读取堵塞，会抛出异常
                String s = new String(buffer, 0, len);
                System.out.print(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
